import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:recognition_qrcode/recognition_qrcode.dart';
import 'package:xvideos/hj_page/mine_business/identity/mine_identity_page.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/permission_util.dart';
import 'package:xvideos/hj_utils/utils.dart';
import 'package:xvideos/tools_base/event_bus/event_bus_util.dart';
import 'package:xvideos/tools_base/event_bus/events.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/net/net_manager.dart';

class MineScanLginController extends GetxController {
  QRViewController? scanController;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    scanController?.dispose();
    super.onClose();
  }

  onQRViewCreated(QRViewController controller) {
    scanController = controller;

    scanController?.scannedDataStream.listen((scanData) {
      // setState(() {
      // result = scanData;
      // controller.dispose();
      // Navigator.pop(context, result?.code);
      // });
      loginByQrValue(scanData.code ?? '');
    });
  }

  /// 开启本地相册
  openNativePhoto() async {
    if (await PermissionUtil.checkPhotoPermission()) {
      final images = await ImagePickers.pickerPaths(
        uiConfig: UIConfig(uiThemeColor: Colors.white),
        selectCount: 1,
        showCamera: false,
        cropConfig: CropConfig(enableCrop: false),
      );
      if (images.isNotEmpty) {
        RecognitionManager.recognition(images[0].path ?? '').then((value) {
          loginByQrValue(value.value);
        }).catchError((error) {
          showToast('二维码错误～～');
        });
      }
    }
  }

  /// 开始二维码登录
  loginByQrValue(String qrValue) async {
    if (qrValue.isEmpty) {
      showToast("二维码为空");
      return;
    }
    scanController?.pauseCamera();
    // 删除旧的toekn
    await netManager.setToken(null);
    // 刷新ua
    netManager.userAgent(deviceId: await getDeviceOaid());
    var userInfo = await globalStore.loginByQr(qrValue);
    if (userInfo?.uid == null) {
      showToast("切换账号失败");
      scanController?.resumeCamera();
      return;
    }
    showToast('登录成功');
    eventBus.emit(ReLoginEvent());
  }

  /// 跳转凭证
  jumpToCertificate() => Get.to(MineAccountIdentityPage());
}
